
/**
 * 一些缓存相关的操作方法
 */

import wx from "weixin-js-sdk";

 //apptoken的KEY
const TOKEN_KEY = "APP_TOKEN";

//oauth2.0的token的KEY
const OAUTH_TOKEN_KEY = "OAUTH_TOKEN";

const KEY = 'History'


import { getUa, isMiniProgram} from "utils/utils";

let maxLength = 5;

//普通的token认证管理
const appToken = {

    /**
     * 获取token
     */
    getToken(){
        
        let tokenStr = localStorage.getItem(TOKEN_KEY);
        if(!tokenStr){
            return null;
        }

        let token = JSON.parse(tokenStr);
        return token;
    },

    /**
     * 设置token
     * @param {*} token 
     */
    setToken(token){
        localStorage.setItem(TOKEN_KEY, JSON.stringify(token));
    },

    /**
     * 清除token
     */
    clearToken(){
        localStorage.removeItem(TOKEN_KEY);
    },

    /**
     * 是否已登录
     */
    isLogin(){
        let token = this.getToken();
        if(!token){
            return false;
        }

        return true;
    },

    /**
     * 是否需要授权认证
     */
    isNeedAuth(url){

        if(url.indexOf("/p/") === -1){
            return false;
        }

        return true;
    },

    /**
     * 生成认证头
     */
    generateAuthHeaders(){
        let headers = {};

        let token = this.getToken();
        let sourceChannel = 'WX_MALL'
        if(token){
            headers = {
                "Authorization": "Bearer " + token.accessToken,
            }
            

        }

        if (getUa().isWeixin) {

            if (wx && wx.miniProgram) {

                wx.miniProgram.getEnv(function (res) {
                    if (res.miniprogram) {
                        sourceChannel = 'WX_MINIAPP_USER_LIVE'
                    } else {
                        sourceChannel = 'WX_MALL'
                        // sourceChannel = 'WX_MALL'
                    }
                })
            } else {

            }


        } else {
            sourceChannel = 'H5_MALL'
        }


        headers.sourceChannel = sourceChannel

        if (sourceChannel == 'WX_MINIAPP_USER_LIVE' && sessionStorage.getItem('LIVESESSIONID')) {
            headers.liveSessionId = sessionStorage.getItem('LIVESESSIONID')
        }

        
        sessionStorage.getItem("SHOPID") && (headers.shopId = sessionStorage.getItem("SHOPID"));

        


        return headers;
    }
}

//oauth2.0认证token管理, 微服务版本使用
const oauthToken = {
    /**
    * 获取token
    */
   getToken(){
       
       let tokenStr = localStorage.getItem(OAUTH_TOKEN_KEY);
       if(!tokenStr){
           return null;
       }

       let token = JSON.parse(tokenStr);
       return token;
   },

   /**
    * 设置token
    * @param {*} token 
    */
   setToken(token){
       localStorage.setItem(OAUTH_TOKEN_KEY, JSON.stringify(token));
   },

   /**
    * 清除token
    */
   clearToken(){
       localStorage.removeItem(OAUTH_TOKEN_KEY);
   },

   /**
    * 是否已登录
    */
   isLogin(){
       let token = this.getToken();
       if(!token){
           return false;
       }

       return true;
   },

   /**
    * 是否需要认证
    */
   isNeedAuth(url){
    if(url.indexOf("/p/") === -1){
        return false;
    }

    return true;
   },

   /**
    * 生成认证头
    */
    generateAuthHeaders(){

        let headers = null;
        
        let sourceChannel = 'WX_MALL'
        let token = this.getToken();
        if(token){
            headers = {
                "Authorization": "Bearer " + token.access_token,
            }
        }

       


        if (getUa().isWeixin) {

            if (wx && wx.miniProgram) {

                wx.miniProgram.getEnv(function (res) {
                    if (res.miniprogram) {
                        sourceChannel = 'WX_MINIAPP_USER_LIVE'
                    } else {
                        sourceChannel = 'WX_MALL'
                        // sourceChannel = 'WX_MALL'
                        // alert(2)
                    }
                })
            } else {

            }


        } else {
            sourceChannel = 'H5_MALL'
        }


        headers.sourceChannel = sourceChannel

        if (sourceChannel == 'WX_MINIAPP_USER_LIVE' && sessionStorage.getItem('LIVESESSIONID')) {
            headers.liveSessionId = sessionStorage.getItem('LIVESESSIONID')
        }

        
        sessionStorage.getItem("SHOPID") && (headers.shopId = sessionStorage.getItem("SHOPID"));
       

        return headers;
    },

    
}



const store = {

    History: 'History',
    location:  'location',

    //历史搜索
    getHistory(keyname) {
        let that = this
        const words =  JSON.parse(localStorage.getItem(keyname))
        if(!words){
            return []
        }
        for (let i = 0; i < words.length; i++) {
            if (words[i] == "" || typeof(words[i]) == "undefined" || words[i] == "") {
                words.splice(i,1)
                i= i-1
            }    
        }
        return words
    },
    //添加历史搜索
    addToHistory(keyname , keyword) {
        let that = this
        let words = that.getHistory(keyname)
        if (Object.prototype.toString.call(words) == '[object String]'||Object.prototype.toString.call(words) == '[object Object]') { 
            words = []// 如果words不是数组，则先清空
        }
        let has = keyword?words.includes(keyword):''
        if (!has&&keyword) {
            // 数组末尾 删除 ， keyword 数组第一位
            const length = words.length
            if (length >= maxLength){
                words.pop()
            }
            words.unshift(keyword)
            localStorage.setItem(keyname,JSON.stringify(words))
        }
    },   

    //清除历史搜索缓存
    clearHistory(keyname) {
        localStorage.removeItem(keyname)
    }

    

}


/**
 * 通行证 storage 管理
 */
const passport = {

    PASSPORT_ID_KEY: "passportIdKey",

    /**
     * 获取 第三方登录成功后 生成的通行证密钥
     */
    getPassportIdKey(){
        return sessionStorage.getItem(this.PASSPORT_ID_KEY);
    },

    /**
     * 设置 第三方登录成功后 生成的通行证密钥, 设置到sessionStorage
     * @param {*} passportIdKey 
     */
    setPassportIdKey(passportIdKey){
        sessionStorage.setItem(this.PASSPORT_ID_KEY, passportIdKey);
    },

    /**
     * 清空第三方登录成功后 生成的通行证密钥
     */
    clearPassportIdKey(){
        sessionStorage.removeItem(this.PASSPORT_ID_KEY);
    }
}


/**
 * 生成游客ID visitid
 */

const visit={
    setCookieId(){
        if(!this.getCookieId()){
            let value = this.createUniqueId()
            localStorage.setItem('visitId',value)
        }
    },
    getCookieId(){
       let value = localStorage.getItem('visitId')||''
       return value
    },
    createUniqueId() {
        return Number(Math.random().toString().substr(2)).toString(36); // 转换成十六进制
    }
}





let tokenManage = null;
if(process.env.VUE_APP_ISMICRO == 'true'){//如果是微服务
    tokenManage = oauthToken;
}else{//如果不是
    tokenManage = appToken;
}

export {
    store,
    tokenManage,
    passport,
    visit
 }